import subprocess
import time

class ConfigureServices:
    def __init__(self, services):
        self.services = services
        self.successful = 0
        self.failed     = 0
        self.oo_sync    = 0

    def configure(self):
        print "\033[1;36m- Configuring Services\033[1;m"
        runtime_start = time.time()
        # Sort list by weight
        self.services.sort(key=lambda d: (d['weight']))

        for service in self.services:
            p = subprocess.Popen(['/sbin/service', service['name'], 'status'],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
            out, err = p.communicate()
            # Service is up and running.
            if p.returncode == 0:
                self.successful += 1
            # Error while checking status, report failure.
            if p.returncode == 1:
                print "\033[1;31m  Starting %s failed: %s\033[1;m" % (service['name'], err.strip('\n'))
                self.failed += 1
            # Service is not running, try and start it.
            if p.returncode == 3:
                s = subprocess.Popen(['/sbin/service', service['name'], 'start'],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
                start_out, start_err = s.communicate()
                if s.returncode == 0:
                    print "  %s out of sync.. %s" % (service['name'], start_out.strip('\n'))
                    self.oo_sync += 1
                    self.successful += 1
                else:
                    print "\033[1;31m  Starting %s failed: %s\033[1;m" % (service['name'], start_err)
                    self.failed += 1

        # Collect Stats
        runtime_end = time.time()
        runtime = (runtime_end - runtime_start)

        stats = {
            'runtime'   : runtime,
            'successful': self.successful,
            'failed'    : self.failed,
            'oo_sync'   : self.oo_sync
        }

        return stats

    def restart(self, service_list=None):
        pass

    def compare(self,x,y):
        weight_diff = int(y['weight']) - int(x['weight'])
        return weight_diff
